package cn.z2huo.knowledge.basic.datetime.simpledateformat.threads;

import cn.hutool.core.collection.ConcurrentHashSet;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *
 * @author z2huo
 */
class MultiThreadThreadLocalTest {

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static final ThreadLocal<DateFormat> DATE_FORMAT_HOLDER = ThreadLocal.withInitial(
            () -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(100);

        ConcurrentHashSet<String> set = new ConcurrentHashSet<>();

        try (ExecutorService threadPool = Executors.newFixedThreadPool(10)) {

            for (int i = 0; i < 100; i++) {
                Calendar calendar = Calendar.getInstance();
                int finalI = i;
                threadPool.execute(() -> {
                    calendar.add(Calendar.DATE, finalI);
                    String dateFormat = DATE_FORMAT_HOLDER.get().format(calendar.getTime());
                    set.add(dateFormat);
                    countDownLatch.countDown();
                });
            }
        }

        countDownLatch.await();
        System.out.println(set.size());
    }

}
